import React, { FC, useState, useEffect, useCallback, useMemo } from 'react';
import { Input, Space, Badge, TreeSelect, Switch, InputNumber } from 'antd';
import { isNil, isArray, isEmpty } from 'lodash';
import { ColumnType } from 'antd/lib/table';

import { Content } from '@components/Page';
import CollapseQueryBar from '@components/CollapseQueryBar';
import Table from '@components/Table';
import Button from '@components/Button';
import { useForm, useWatch } from '@components/Form';
import EditDrawerForm from '@components/EditDrawerForm';

import { getDictionaryListApi, getDeptApi } from '@services/service';
import { Status } from '@enumTypes/enumTypes';
import { TableAlignType } from '@/enumTypes/table';
import {
  useResetFormOnCloseModal,
  generateCommonSelect,
  generateCommonDeleteModal,
  setOtherTypeValue
} from '@utils/renderer';
import { getPropValueByValue, getFormValues } from '@utils/util';
import request from '@utils/request';
import notification from '@utils/notification';
import { COMMON_REQUIRE_RULE, COMPLETELY_FILL_STYLE, VALIDATE_COMMON_CODE } from '@/utils/config';

const { TextArea } = Input;

const DeptSetting: FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [saveLoading, setSaveLoading] = useState<boolean>(false);

  // 字典数据
  const [statusList, setStatusList] = useState<any[]>([]);
  const [catalogueData, setCatalogueData] = useState<any[]>([]);

  const [deptData, setDeptData] = useState<any[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [selectedRows, setSelectedRows] = useState<any[]>([]);

  const [operationType, setOperationType] = useState<string>('');
  const [openFlag, setOpenFlag] = useState<boolean>(false);

  const [currentLine, setCurrentLine] = useState<any>({}); // 当前编辑行数据(旧)

  const [queryForm] = useForm(); // 查询表单
  const [editForm] = useForm(); // 编辑表单

  const watchType = useWatch('type', editForm);

  /** 查询设置字典数据 */
  const handleQueryDictionaryList = useCallback(() => {
    getDictionaryListApi(['RB_STATUS']).then((res: any) => {
      if (isArray(res)) {
        const [statusList = []] = res || [];
        setStatusList(statusList);
      }
    });
  }, []);

  /** 查询表格数据 */
  const handleQueryData = useCallback((params: any) => {
    setLoading(true);

    getDeptApi(params)
      .then((res: any) => {
        if (res && isArray(res)) {
          setDeptData(res);
          // 查询重置勾选
          setSelectedRowKeys([]);
          setSelectedRows([]);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  useEffect(() => {
    handleQueryDictionaryList();
    handleQueryData({});
  }, [handleQueryData, handleQueryDictionaryList]);

  useResetFormOnCloseModal({ form: editForm, openFlag });

  /** 表单查询 */
  const handleSearch = useCallback(
    (values: any) => {
      handleQueryData({ ...values });
    },
    [handleQueryData]
  );

  /** 打开 新增|编辑 抽屉 */
  const handleOpenEditDrawer = useCallback(
    (type: string, record: any = {}) => {
      // 设置操作类型
      setOperationType(type);

      const _record = { ...record };
      delete _record.children;
      // 设置当前编辑行数据
      setCurrentLine(_record);

      if (type === 'update') {
        // 设置抽屉表单数据
        editForm.setFieldsValue(_record);
      }

      setSaveLoading(true);
      getDeptApi({ status: Status.enable })
        .then((res: any) => {
          if (res && isArray(res)) {
            setCatalogueData(res);
          }
        })
        .finally(() => {
          setSaveLoading(false);
        });

      // 打开抽屉
      setOpenFlag(true);
    },
    [editForm]
  );

  /** 保存 */
  const handleSave = useCallback(async () => {
    // 表单未修改
    if (!editForm.isFieldsTouched()) {
      // 关闭抽屉
      setOpenFlag(false);
      return;
    }

    // 校验获取值
    const fields = await editForm.validateFields();

    // 校验通过
    if (fields) {
      setSaveLoading(true);
      request({
        url: '/system/dept',
        method: operationType === 'update' ? 'PUT' : 'POST',
        data: { ...currentLine, ...fields }
      })
        .then(async (res: any) => {
          if (res) {
            notification.success();
            // 关闭抽屉
            setOpenFlag(false);
            const params = await getFormValues(queryForm);
            // 查询最新数据
            handleQueryData(params);
          }
        })
        .finally(() => {
          setSaveLoading(false);
        });
    }
  }, [currentLine, editForm, handleQueryData, operationType, queryForm]);

  /** 删除 */
  const handleDelete = useCallback(() => {
    if (isEmpty(selectedRowKeys)) return;

    generateCommonDeleteModal({
      title: '是否确定删除这些部门 ?',
      onOk() {
        setLoading(true);
        request({
          url: '/system/dept',
          method: 'DELETE',
          data: selectedRowKeys
        })
          .then(async (res: any) => {
            if (res) {
              notification.success();
              const params = await getFormValues(queryForm);
              // 查询最新数据
              handleQueryData(params);
            }
          })
          .finally(() => {
            setLoading(false);
          });
      }
    });
  }, [handleQueryData, queryForm, selectedRowKeys]);

  /** 查询条配置列表 */
  const queryFromItems = useMemo(
    () => [
      {
        name: 'name',
        label: '部门名称',
        children: <Input />
      },
      {
        name: 'code',
        label: '部门编码',
        children: <Input />
      },
      {
        name: 'status',
        label: '状态',
        initialValue: 1,
        children: generateCommonSelect(statusList)
      }
    ],
    [statusList]
  );

  /** 编辑表单配置列表 */
  const editFormItems = useMemo(
    () => [
      {
        name: 'parentId',
        label: '上级部门',
        children: (
          <TreeSelect
            style={COMPLETELY_FILL_STYLE}
            treeData={catalogueData}
            fieldNames={{
              value: 'id',
              label: 'name'
            }}
            allowClear
          />
        )
      },
      {
        name: 'name',
        label: '部门名称',
        rules: [COMMON_REQUIRE_RULE],
        children: <Input />
      },
      {
        name: 'code',
        label: '部门编码',
        tooltip: VALIDATE_COMMON_CODE.message,
        rules: [COMMON_REQUIRE_RULE, VALIDATE_COMMON_CODE],
        children: <Input disabled={operationType === 'update'} allowClear />
      },
      {
        name: 'status',
        label: '状态',
        valuePropName: 'checked',
        rules: [COMMON_REQUIRE_RULE],
        ...setOtherTypeValue(1, 0),
        children: <Switch checkedChildren="启用" unCheckedChildren="禁用" />
      },
      {
        name: 'weight',
        label: '序号',
        children: <InputNumber precision={0} min={0} style={COMPLETELY_FILL_STYLE} />
      },
      {
        name: 'remark',
        label: '备注',
        children: <TextArea />
      }
    ],
    [editForm, catalogueData, operationType, watchType, setOtherTypeValue]
  );

  /** 表格列配置 */
  const columns: ColumnType<any>[] = useMemo(
    () => [
      {
        title: '部门名称',
        dataIndex: 'name',
        key: 'name',
        width: '20%'
      },
      {
        title: '部门编码',
        dataIndex: 'code',
        key: 'code',
        width: '10%'
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        align: TableAlignType.center,
        width: 100,
        render: (value: any) => {
          return (
            !isNil(value) && (
              <Space>
                <Badge status={Status.enable === value ? 'success' : 'error'} />
                {getPropValueByValue(value, statusList)}
              </Space>
            )
          );
        }
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark'
      },
      {
        title: '操作',
        key: 'operation',
        align: 'center',
        width: 120,
        fixed: 'right',
        render: (_: any, record: any = {}) => {
          return (
            <>
              <Button type="link" onClick={() => handleOpenEditDrawer('update', record)}>
                修改
              </Button>
            </>
          );
        }
      }
    ],
    [handleOpenEditDrawer, statusList]
  );

  /** 勾选配置 */
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[], newSelectedRows: any[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
      setSelectedRows(newSelectedRows);
    },
    checkStrictly: false // 开启父子节点关联
  };

  return (
    <Content loading={loading}>
      <CollapseQueryBar
        form={queryForm}
        queryFromItems={queryFromItems}
        handleSearch={handleSearch}
      />
      <div style={{ textAlign: 'right', marginBottom: 8 }}>
        <Space>
          <Button type="primary" onClick={() => handleOpenEditDrawer('create')}>
            新增
          </Button>
          <Button type="primary" danger disabled={!selectedRowKeys.length} onClick={handleDelete}>
            删除
          </Button>
        </Space>
      </div>
      <Table
        rowKey="id"
        // defaultExpandAllRows只会在第一次渲染时触发，那时，table的数据往往为空
        // 设定一个key值，key值一旦改变会自动变成新的组件
        key={deptData.length}
        columns={columns}
        dataSource={deptData}
        pagination={false}
        rowSelection={rowSelection}
        expandable={{
          defaultExpandAllRows: true
        }}
        scroll={{ y: '65vh' }}
      />
      {openFlag && (
        <EditDrawerForm
          title={operationType === 'update' ? '编辑' : '新增'}
          initialValues={{ status: 1 }}
          openFlag={openFlag}
          setOpenFlag={setOpenFlag}
          form={editForm}
          handleSave={handleSave}
          loading={saveLoading}
          formItems={editFormItems}
        />
      )}
    </Content>
  );
};

export default DeptSetting;
